<?php

namespace App\Http\Controllers\background;

use App\Http\Controllers\Controller;
use App\Models\Mysql\XnIp;
use App\Models\Mysql\XnMechantBalance;
use App\Models\Mysql\XnMechantInfos;
use App\Models\Mysql\XnMerchantBill;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Mysql\XnMerchant;
class MechantController extends Controller
{

    // use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    // 获取商户数据
    public function mechantlist(Request $request){
        $mechant_name = $request->post('mechant_name','');
        $phone = $request->post('phone','');
        $start_time =$request->post('start_time','');
        $end_time =$request->post('end_time','');
        $mechant_number = $request->post('mechant_number','');
        $arr = [];
        if(!empty($mechant_name)){
            $arr[] = ['nickname','like','%'.$mechant_name.'%'];
        }
        if(!empty($phone)){
            $arr[] = ['phone','=',$phone];
        }

        if(!empty($mechant_number)){
            $arr[] = ['merchant_number','=',$mechant_number];
        }
       $res =  XnMerchant::where($arr) -> orderBy('time','desc') -> paginate(10) -> toArray();
        foreach($res['data'] as $k => $v){
            $res['data'][$k]['balance'] = round($v['balance'] - $v['deduction_balance'],4);
        }
        return successly($res);
    }

    // 给商户加款
    public function rechargeMoney(Request $request){
        $money = $request->post('money','');
        $fund_t = $request->post('funds_t','');
        $remarks =$request->post('remarks','');
        $user =$request->post('user','');
        $mechant_number =$request->post('mechant_number','');
        if(empty($money)){
            return fails('请传金额');
        }
        if(empty($user)){
            return fails('请传用户');
        }
        if(empty($mechant_number)){
            return fails('请传商户号');
        }
        if(empty($fund_t)){
            return fails('请传加款类型');
        }
        if(empty($remarks)){
            return fails('请传备注');
        }
        $info =XnMerchant::where('merchant_number',$mechant_number)
            -> select('merchant_number','balance','nickname','deduction_balance')
            -> first()
            ->toArray();
        $balance = $info['balance'] - $info['deduction_balance'];
        if($fund_t == 1){
           Log::channel('fundAdd')->info('加款信息:'.$mechant_number.'商户正常加款'.$money.',余额为'.($balance + $money));
        }else if($fund_t == 2){
            Log::channel('fundAdd')->info('加款信息:'.$mechant_number.'商户授信加款'.$money.',余额为'.($balance + $money));
        }
        $time = date('Y-m-d H:i:s',time());
        DB::connection(request()->get('db', 'supplier'))->beginTransaction();
        try{
            XnMerchantBill:: insert([
                'merchant_number' =>$mechant_number,
                'time'=>$time,
                'status' => 1,
                'before_transaction_balance' => $balance,
                'transaction_amount' => $money,
                'after_transaction_balance' => ($balance + $money),
                'merchant_order' => date('YmdHis').rand(1000000000,9999999999),
                'trading_status'=>1,
                'Operator'=>$user,
                'funds_type'=>$fund_t,
                'remarks' => $remarks,
                'mechant_name'=>$info['nickname']
            ]);
            XnMerchant::where('merchant_number',$mechant_number)
                -> increment('balance',$money);
            DB::connection(request()->get('db', 'supplier'))->commit();
            $arr = ['time'=>$time,'beforemoney'=>$balance,'aftermoney'=>($balance + $money)];
            return successly($arr);
        }catch (\Exception $e){
            DB::connection(request()->get('db', 'supplier'))->rollBack();
           //dd($e ->getMessage());exit;
            return fails('加款失败');
        }

    }

    // 商户扣款
    public function cutMoney(Request $request){
        $money = $request->post('money','');
        $user =$request->post('user','');
        $mechant_number =$request->post('mechant_number','');
        if(empty($money)){
            return fails('请传金额');
        }
        if(empty($user)){
            return fails('请传用户');
        }
        if(empty($mechant_number)){
            return fails('请传商户号');
        }
        $info = XnMerchant::where('merchant_number',$mechant_number)
            -> select('merchant_number','balance','nickname','deduction_balance')
            -> first()
            -> toArray();
        $balance = $info['balance'] - $info['deduction_balance'];
        if($balance<$money){
            return fails('余额已不足以扣款');
        }
        Log::channel('fundAdd')->info('扣款信息:'.$mechant_number.'商户扣款'.$money.',余额为'.($balance - $money));
        $time = date('Y-m-d H:i:s',time());
        DB::connection(request()->get('db', 'supplier'))->beginTransaction();
        try{
            XnMerchantBill:: insert([
                'merchant_number' =>$mechant_number,
                'time'=>$time,
                'status' => 4,
                'before_transaction_balance' => $balance,
                'transaction_amount' => $money,
                'after_transaction_balance' => ($balance - $money),
                'merchant_order' => date('YmdHis').rand(1000000000,9999999999),
                'trading_status'=>1,
                'Operator'=>$user,
                'mechant_name'=>$info['nickname']
            ]);
            XnMerchant::where('merchant_number',$mechant_number)
                -> increment('deduction_balance',$money);
            DB::connection(request()->get('db', 'supplier'))->commit();
            $arr = ['time'=>$time,'beforemoney'=>$balance,'aftermoney'=>($balance - $money)];
            return successly($arr);
        }catch (\Exception $e){
            DB::connection(request()->get('db', 'supplier'))->rollBack();
            // var_dump($e ->getMessage());exit;
            return fails('扣款失败');
        }
    }
    // 商户加款接口
    public function addFunds(Request $request){
            $Merchant_number = $request->post('Merchant_number','');
            $money = $request->post('money','');
            $Operator = $request->post('Operator','');
            if(empty($money)){
                return fails('请传金额');
            }
            if(empty($Operator)){
                return fails('请传用户');
            }
            if(empty($Merchant_number)){
                return fails('请传商户号');
            }
            $funds_type = $request->post('funds_type','');
            $remarks = $request->post('remarks','');
            $come_from = $request->post('come_from','');
            if(preg_match('/^1[3456789]{1}\d{9}$/',$Merchant_number)){
                $where[] = ['phone',$Merchant_number];
            }else{
                $where[] =['merchant_number',$Merchant_number];
            }
            $mechant_infos = XnMerchant::where($where)
                -> select('nickname','merchant_number','balance','phone','deduction_balance')
                -> first()
                -> toArray();

            if(!$mechant_infos){
                return fails('未查询到该商户信息');
            }
            $time = date('Y-m-d H:i:s',time());
            // 启动事务
            DB::connection(request()->get('db', 'supplier'))->beginTransaction();
            try{
                $balance = $mechant_infos['balance'] - $mechant_infos['deduction_balance'];
                $addInfo = [
                    'merchant_number' =>$mechant_infos['merchant_number'],
                    'time'=>$time,
                    'status' => 1,
                    'before_transaction_balance' => $balance,
                    'transaction_amount' => $money,
                    'after_transaction_balance' => ($balance + $money),
                    'merchant_order' => date('YmdHis').rand(1000000000,9999999999),
                    'trading_status'=>1,
                    'Operator'=>$Operator,
                    'funds_type'=>$funds_type,
                    'remarks' => $remarks,
                    'come_from'=>$come_from,
                    'mechant_name'=>$mechant_infos['nickname']
                ];
                XnMerchantBill:: insert($addInfo);
                XnMerchant::where($where)
                    -> increment('balance',$money);
                // 提交事务
                DB::connection(request()->get('db', 'supplier'))->commit();
                if($funds_type == 1){
                    Log::channel('fundAdd')->info('加款信息:'.$Merchant_number.'商户正常加款'.$money.',余额为'.($balance + $money));
                }else if($funds_type == 2){
                    Log::channel('fundAdd')->info('加款信息:'.$Merchant_number.'商户授信加款'.$money.',余额为'.($balance + $money));
                }
                $returnInfo = [
                    'merchant_number' => $addInfo['merchant_number'],
                    'nickname' =>$mechant_infos['nickname'],
                    'phone' => $mechant_infos['phone'],
                    'chinesemoney'=>Number_conversion_to_uppercase($addInfo['transaction_amount']),
                    'before_transaction_balance' => $addInfo['before_transaction_balance'],
                    'transaction_amount' => $addInfo['transaction_amount'],
                    'after_transaction_balance' => $addInfo['after_transaction_balance'],
                    'time' => $time,
                    'funds_type'=>$funds_type,
                    'come_from'=>$come_from
                ];
                return successly($returnInfo);
            } catch (\Exception $e) {
                // 回滚事务
                DB::connection(request()->get('db', 'supplier'))->rollBack();
                Log::channel('error')->info('加款失败'.$e -> getMessage());
                return fails('加款失败');
            }
    }
    // 商户开关
    public function mechantopen(Request $request){
        $is_ipen = $request->post('is_open','');
        if(empty($is_ipen)){
            return fails('请传参数');
        }
        $mechant_number =$request->post('mechant_number','');
        if(empty($mechant_number)){
            return fails('请传商户号');
        }
        XnMerchant::where('merchant_number',$mechant_number)
            -> update(['merchant_type' =>$is_ipen]);
        return successly();
    }

    // ip白名单展示
    public function iplist(Request $request){
        $mechant_name = $request->post('mechant_name','');
        $where  = [];
        if(!empty($mechant_name)){
            $where = ['mechant_name','like','%'.$mechant_name.'%'];
        }
        $res = XnIp::where($where)
            -> orderBy('create_time','desc')
            -> paginate(10)
            -> toArray();
        if(!empty($res)){
            return successly($res);
        }else{
            return fails('暂无数据');
        }
    }

    // ip白名单添加
    public function ipaddinfo(Request $request){
        $ipiinfo = $request->post();
        if(empty($ipiinfo['merchant_number'])){
            return fails('请传商户号');
        }
        if(empty($ipiinfo['info'])){
            return fails('请传ip信息');
        }
        if(empty($ipiinfo['mechant_name'])){
            return fails('请传商户名称');
        }
        $res = XnIp:: insert([
            'info' =>$ipiinfo['info'],
            'merchant_number'=>$ipiinfo['merchant_number'],
            'create_time' => date('Y-m-d H:i:s',time()) ,
            'mechant_name' => $ipiinfo['mechant_name']
        ]);
        if(!$res){
            return fails('添加失败');
        }
        return  successly();
    }
    // ip白名单删除
    public function ipdelinfo(Request $request){

        $ipiinfo = $request->post('i_id');
        if(empty($ipiinfo)){
            return fails('请传参数');
        }
        $res = XnIp:: where('id','=',$ipiinfo) -> delete();
        if(!$res){
            return fails('删除失败');
        }
        return successly();
    }
    // 商户认证列表
    public function identifyInfo(Request $request){
        $mechant_number = $request->post('mecahnt_number');
        $status = $request->post('status');
        $type = $request->post('type');
        $where= [];
        if(!empty($mechant_number)){
            $where[] = ['merchant_number','=',$mechant_number];
        }
        if(!empty($status)){
            $where[] = ['status','=',$status];
        }
        $where[] = ['user_type','=',$type];
        $res = XnMerchant::where($where) -> with('mechantinfos')->orderByDesc(
            XnMechantInfos::select('reply_time')
            ->whereColumn('merchant_id','xn_merchant.id')
            ->limit(1)
        )
            ->paginate(10)
            ->toArray();
        if(!$res){
            return fails('获取失败');
        }
        return  successly($res);
    }
    // 商户审核
    public function mecahntexam(Request $request){
        $id = $request->post('m_id');
        $status = $request -> post('status');
        $reason = $request -> post('refuse_reason');
        DB::connection(request()->get('db', 'supplier'))->beginTransaction();
        try {
            $o_status = XnMerchant::find($id);
            $o_status->status = $status;
            $o_status->save();
            XnMechantInfos::where('merchant_id',$id) -> update(['refuse_reason'=>$reason]);
            DB::connection(request()->get('db', 'supplier'))->commit();
            return successly();
        }catch (\Exception $e){
            DB::connection(request()->get('db', 'supplier'))->rollBack();
            //var_dump($e ->getMessage());
            return fails('审核失败reason');
        }

    }
    public function ZeroBalance(Request $request){
        $start_date = $request -> post('start_date');
        $end_date = $request -> post('end_date');
        $merchant_number = $request -> post('merchant_number');
        $data = getDateFromRange($start_date,$end_date);
        $a = [];
        $conditon[]=['merchant_number','=',$merchant_number];
        foreach($data as $k => $v){
            $where = $conditon;
            $where[]= ['ctime','=',$v];
            $infos =XnMechantBalance::where($where) -> first();
            if($infos){
                $a[] = $infos ->toArray();
            }
        }
        /*$sort = array_column($a, 'ctime');
        if($sort){
            array_multisort($sort, SORT_DESC,$a);
        }*/
        $b = arraySort($a,'ctime');
        if($b){
            $count = count($b);
            return successly($b,200,$count);
        }else{
           return fails('未查询到数据');
        }
    }
}
